import React, {
  useLayoutEffect,
  useEffect,
  useRef,
  useState,
  useCallback,
  useMemo,
  useDebugValue,
} from "react";
import { Interface } from "readline";

const useCookie = (name:string, initValue:string = '') => { 
  // 1.获取cookie
  const getCookie = () => {
    const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]*)(;|$)`)) 
    // 0 xiaoman=xxx 1 '' 2 xxx
    return match ? match[2] : initValue
  }
  const [cookie, setCookie] = useState(getCookie())

  // 2.更新cookie
  const updateCookie = (value:string) => {
    document.cookie = `${name}=${value}`
    setCookie(value)
  }

  // 3.删除cookie 
  const deleteCookie = () => {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;` // 直接过期删除
    setCookie("")
  }
  useDebugValue(cookie,(value) => {
    return `Cookie: ${value}`
  })
  return [cookie, updateCookie, deleteCookie]  as const // 设置类型为元组
}

function App() { 
  const [cookie, updateCookie, deleteCookie] = useCookie("xxx", "value")
  return ( 
    <>
    <div>{cookie}</div>
    <button onClick={()=> updateCookie('upate-xxx')}>更新</button>
    <button onClick={()=> deleteCookie()}>删除</button>
    </>
  )

}

export default App;
